package com.allenkerr.service.impl;

import java.util.List;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import com.allenkerr.dao.ArticleRepository;
import com.allenkerr.model.Article;
import com.allenkerr.service.ArticleService;
import com.allenkerr.vo.Result;

/**
 * @author 小柯
 * @date 2017/11/10
 */
@Service
public class ArticleServiceImpl implements ArticleService {

  @Autowired
  private ArticleRepository articleDao;
  @Autowired
  private ElasticsearchTemplate esTemplate;

  @Override
  public Result saveArticles(List<Article> articles) {
    Iterable<Article> savedArticles = articleDao.save(articles);
    return Result.success(savedArticles);
  }

  @Override
  public Result findArticles(String queryString) {
    QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder(queryString);
    AggregatedPageImpl<Article> searchResult = (AggregatedPageImpl<Article>) articleDao.search(queryBuilder);
    return Result.success(searchResult.getContent());
  }

  @Override
  public Result findArticlesWithNativeSearchQueryBuilder(String title) {

    NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.matchAllQuery())
            .withFilter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("title", title)))
            .build();

    AggregatedPage<Article> articlePage = esTemplate.queryForPage(nativeSearchQuery, Article.class);

    return Result.success(articlePage.getContent());
  }


}
